package com.alex.server.controller;

import com.alex.server.pojo.Menu;
import com.alex.server.pojo.MenuRole;
import com.alex.server.pojo.RespBean;
import com.alex.server.pojo.Role;
import com.alex.server.service.IMenuRoleService;
import com.alex.server.service.IMenuService;
import com.alex.server.service.IRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 权限组
 */
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissController {
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private IMenuService iMenuService;
    @Autowired
    private IMenuRoleService iMenuRoleService;
    @ApiOperation(value = "获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles(){
        return iRoleService.list();
    }
    @ApiOperation("添加角色")
    @PostMapping("/role")
    public RespBean addRole(@RequestBody Role role){
        if (!role.getName().startsWith("ROLE_")){
            role.setName("ROLE_"+role.getName());
        }
        boolean save = iRoleService.save(role);
        if (save){
            return RespBean.success("保存成功");
        }else
            return RespBean.error("保存失败");
    }
    @ApiOperation("删除角色")
    @DeleteMapping("/role/{rid}")
    public RespBean deleteRole(@PathVariable Integer rid){
        if (iRoleService.removeById(rid)){
            return RespBean.success("删除成功");
        }else
            return RespBean.error("删除失败");
    }
    @ApiOperation(value = "查询所有菜单")
    @GetMapping("/menus")
    public List<Menu> getAllMenu(){
        List<Menu> allMenus = iMenuService.getAllMenus();
        return allMenus;
    }
    @ApiOperation(value = "根据角色id查询菜单id")
    @GetMapping("/mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid){
        List<Integer> mids = iMenuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid)).stream().map(MenuRole::getMid)
                .collect(Collectors.toList());
 //       List<String> menu=new ArrayList<>();
//        for (Integer mid:mids){
//            menu.add(iMenuService.getById(mid).getName());
//        }
        return mids;
    }
    @ApiOperation("跟新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(@RequestParam Integer rid ,Integer[] mids){
        return iMenuRoleService.updateMenuRole(rid,mids);
    }

}
